package cn.rubintry.bug.hunting.common.utils;

import android.os.Handler;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;

public class OkhttpDownloadUtils {

    public static final String TAG = "OkhttpDownloadUtils";

    private static final OkHttpClient client = new OkHttpClient();

    private static Set<DownloadTask> downloadTasks = new HashSet<>();

    public static void downloadFile(String url, String localFilePath , DownloadListener listener) throws IOException {
        if(downloadTasks.isEmpty()){
            new Thread(new DownloadTask(url , localFilePath , listener)).start();
        }
    }


    public interface DownloadListener{
        void onProgress(int progress);
        void onFinish(File apkFile);
    }


    private static class DownloadTask implements Runnable {

        private String url;
        private String localFilePath;
        private DownloadListener listener;

        public DownloadTask(String url, String localFilePath, DownloadListener listener) {
            this.url = url;
            this.localFilePath = localFilePath;
            this.listener = listener;
        }

        @Override
        public void run() {
            downloadTasks.add(this);
            File localFile = new File(localFilePath);
            long alreadyDownloadedBytes = localFile.exists() ? localFile.length() : 0;

            // 构建Request，包含Range头信息以实现断点续传
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Range", "bytes=" + alreadyDownloadedBytes + "-")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    listener.onFinish(localFile);
                    return;
                }

                // 创建或打开本地文件用于追加写入
                FileOutputStream out = new FileOutputStream(localFilePath, true);

                // 获取远程文件总长度
                long totalLength = response.body().contentLength();
                long downloadedSoFar = alreadyDownloadedBytes;

                InputStream inputStream = response.body().byteStream();
                byte[] buffer = new byte[4096];
                int read;

                while ((read = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                    downloadedSoFar += read;

                    // 可以在此输出下载进度
                    listener.onProgress((int) (downloadedSoFar / (float)totalLength * 100));
                    LogUtils.d("进度: " + downloadedSoFar / (float)totalLength * 100 + "%   路径：" + localFilePath);
                    if(downloadedSoFar / (float)totalLength == 1){
                        listener.onFinish(localFile);
                    }
                }

                out.flush();
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    public static void clearTask(){
        downloadTasks.clear();
    }
}
